var app = getApp();
const regeneratorRuntime = require('../../../utils/runtime.js');
let innerAudioContext = wx.createInnerAudioContext(); //创建音频实例
const recordmanage = wx.getRecorderManager()
Page({
 
  onReady: function (e) {
  },

  data: {
    loading: false,
    plain: false,
    disabled: false,//按钮一旦点击提交 则不能操作

    isbreaking: true,
    imageurl: '',//新封面
    oldimgurl: '',//旧封面
    lyimage: app.myUlife.ulifeUrl + '/wx/voice_btn_icon_n.png',//默认图片 
    xturl: app.myUlife.ulifeUrl + "/",
    musicmc: '',//新音频名称
    musicUrl: '',//新音频地址
    formatedPlayTime: '00:00',
    playStatus: true, //未播放的图片
    curTimeVal: 0,
    slider_value: 0,//设置初始滑块位置为0

    readid:'',
    pname: '',
    author: '',
    nj: '',
    bj: '',
    pcontent: '',
    fm: '',

    scnrimage:[],//诗词内容临时图片
    scnrurls: [],//诗词内容图片

    musicarr: [],//语音语音临时文件
    musicurl:[],//诗词语音文件
  },

  /**
    * 生命周期函数--监听页面加载
    */
  onLoad: function (options) {
    var usid = wx.getStorageSync('usid');
    if (!usid) {
      wx.reLaunch({
        url: '../../../pages/login/login'
      })
      return;
    }
    this.setData({
      readid: options.readid
    })

   
    this.getPoetryReadById();//查询诗词
  },

  
  getPoetryReadById: function(e) {
    var that = this;
    var readid = this.data.readid;
    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/getPoetryReadById.html',
      data: {
        readid: readid,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var datas = res.data;
        that.setData({
          pname: datas.PNAME,
          author: datas.AUTHOR,
          nj: datas.NJ,
          pcontent: datas.PCONTENT,
        })
        
        if (datas.FM){
          that.setData({
            imageurl: that.data.xturl + datas.FM,
            oldimgurl: that.data.xturl + datas.FM,
            fm: datas.FM
          })
        }

        if (datas.BJ) {
          that.setData({
            bj: datas.BJ
          })
        }

        if (datas.scnr) {
          that.setData({
            scnrimage: datas.scnr
          })
        }

        if (datas.yy) {
          that.setData({
            musicarr: datas.yy
          })
        }

        wx.createSelectorQuery().select('#editor').context(function (res) {
          that.editorCtx = res.context
          if (datas.PCONTENT) {
            that.editorCtx.setContents({
              html: datas.PCONTENT,
              success: (res) => {
                console.log(res)
              },
              fail: (res) => {
                console.log(res)
              }
            })
          }
        }).exec();

        

      }
    })
  },


  //开始录音
  ksly: function (e) {
    wx.showLoading({
      title: '录音中....',
    })
    const options = {
      duration: 600000,//指定录音的时长，单位 ms
      sampleRate: 44100,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 192000,//编码码率
      format: 'aac',//音频格式，有效值 aac/mp3
      frameSize: 50//指定帧大小，单位 KB
    }
    recordmanage.start(options)
    this.setData({
      isbreaking: true
    });
  },



  jsly: function (e) {
    var that = this;
    recordmanage.stop(); //先停止录音
    recordmanage.onStop((res) => {  //监听录音停止的事件
      if (res.duration < 1000) {
        wx.showToast({
          title: '录音时间太短'
        })
        wx.hideLoading();
        return;
      } else {
        this.setData({
          isbreaking: false
        })
        var tempFilePath = res.tempFilePath; // 文件临时路径
        that.setData({
          musicUrl: tempFilePath
        })
        that.setData({
          curTimeVal: 0,
          formatedPlayTime: '00:00',
          playStatus: true, //图片展示为未播放  
        })
        innerAudioContext.seek(0);
        wx.hideLoading();
      }
    });
  },




  //上传图片
  uploadimage: function () {
    var that = this;
    wx.chooseImage({
      count: 1, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        that.setData({
          imageurl: res.tempFilePaths[0]
        })
      }
    });
  },


  //删除图片
  delImage: function (e) {
    var that = this;
    that.setData({
      imageurl: ""
    })
  },

  //预览图片
  viewimage: function (e) {
    var imageurl = this.data.imageurl;
    wx.previewImage({
      current: imageurl, // 当前显示图片的http链接
      urls: [imageurl] // 需要预览的图片http链接列表
    })
  },




//..............诗词语音播放start.................
  //开始播放
  ksbf: function (e) {
    let that = this
    that.setData({ playStatus: false })
    var musicUrl = that.data.musicUrl; //音频url
    innerAudioContext.src = musicUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.play();
    innerAudioContext.onPlay((res) => {
      innerAudioContext.onTimeUpdate((res) => {
        that.setData({
          duration: innerAudioContext.duration.toFixed(2) * 100,
          curTimeVal: innerAudioContext.currentTime.toFixed(2) * 100,
          formatedPlayTime: this.formatTime(innerAudioContext.currentTime)
        })
        var per = (innerAudioContext.currentTime / innerAudioContext.duration) * 100;
        that.setData({
          slider_value: per//设置slider滑块所在位置
        })
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
          that.setStopState(that)
        }
        innerAudioContext.onEnded(() => {
          that.setStopState(that)
        })
      })
    })
  },
  setStopState: function (that) {
    that.setData({
      curTimeVal: 0,
      formatedPlayTime: '00:00',
      playStatus: true, //图片展示为未播放  
    })
    innerAudioContext.seek(0);
    innerAudioContext.stop();
  },
  //结束播放
  canel_handover() {
    // innerAudioContext.offPause(); //取消录音暂停
    innerAudioContext.pause(); //语音暂停
    this.setData({
      playStatus: true
    })
  },
  listenerSlider: function (e) {
    var per = e.detail.value;
    var currentTime = (per / 100) * innerAudioContext.duration;
    innerAudioContext.seek(currentTime);//通过滑块控制音频进度
    this.formatTime(currentTime)
  },
  formatTime: (time) => {
    time = Math.floor(time);
    var m = Math.floor(time / 60).toString();
    m = m.length < 2 ? '0' + m : m;
    var s = (time - parseInt(m) * 60).toString();
    s = s.length < 2 ? '0' + s : s;
    return m + ':' + s;
  },
  removePlay: function () {
    this.setData({
      curTimeVal: 0,
      formatedPlayTime: '00:00',
      playStatus: true, //图片展示为未播放  
      musicUrl: ''
    })
    innerAudioContext.stop();
    this.setData({
      isbreaking: true
    })
  },
//..............诗词语音播放end.................



  pnameinput(e) {
    this.setData({
      pname: e.detail.value
    })
  },

  authorinput(e) {
    this.setData({
      author: e.detail.value
    })
  },

  njinput(e) {
    this.setData({
      nj: e.detail.value
    })
  },


  bjinput(e) {
    this.setData({
      bj: e.detail.value
    })
  },

  pcontentinput(e) {
    var that = this;
    this.editorCtx.getContents({
      success: (res) => {
        that.setData({
          pcontent: res.html
        });
      },
      fail: res => { console.log("请求失败") }
    })
  },

  musicnametinput(e) {
    this.setData({
      musicmc: e.detail.value
    })
  },



  submitPoteryRead(e) {
    var that = this;
    var pname = this.data.pname;
    if (pname == '') {
      wx.showModal({
        title: '友情提示',
        content: '请填写诗词名称!',
        showCancel: !1,
      })
      return;
    }

    var author = this.data.author;
    if (author == '') {
      wx.showModal({
        title: '友情提示',
        content: '请填写诗词作者姓名!',
        showCancel: !1,
      })
      return;
    }

    var nj = this.data.nj;
    if (nj == '') {
      wx.showModal({
        title: '友情提示',
        content: '请填写接受任务的年级！',
        showCancel: !1,
      })
      return;
    }

    var bj = this.data.bj;

    var pcontent = this.data.pcontent;
    var scnrimage = this.data.scnrimage;
    if (pcontent == '' && scnrimage.length <= 0) {
      wx.showModal({
        title: '友情提示',
        content: '请填写诗词内容或上传诗词内容图片！',
        showCancel: !1,
      })
      return;
    }

    var imageurl = this.data.imageurl;
    if (imageurl == '') {
      wx.showModal({
        title: '友情提示',
        content: '请上传诗词封面以方便展示！',
        showCancel: !1,
      })
      return;
    }


    this.setData({
      disabled: true,
      loading: true
    })
    var musicarr = that.data.musicarr;
    var oldimgurl = that.data.oldimgurl;
    if (imageurl != oldimgurl) {//如果封面重新上传了
      this.uploadImageFile();
    } else if (scnrimage.length>0){
      this.uploadScnrImageFile();
    } else if (musicarr.length > 0) {
      this.uploadMusicFile();
    }else{
      this.savePoteryRead();
    }
  },

  uploadImageFile() {
    var that = this;
    var imageurl = this.data.imageurl;
    wx.uploadFile({ 
      url: app.myUlife.ulifeUrl + '/upload/uploadScdhFm.html', //上传服务器的地址
      filePath: imageurl, //临时路径
      name: 'file',
      header: {
        contentType: "multipart/form-data", //按需求增加
      },
      formData: null,
      success: function (res) {
        var img = JSON.parse(res.data);
        var urls = img.urls;
        that.setData({
          fm: urls
        })
        var scnrimage = this.data.scnrimage;
        var musicarr = that.data.musicarr;
        if (scnrimage.length>0){
          that.uploadScnrImageFile();
        } else if (musicarr.length > 0){
          that.uploadMusicFile();
        }else{
          that.savePoteryRead();
        }
      },
      fail: function (err) {
        wx.hideLoading();
        console.log(err.errMsg);//上传失败
      }
    });
  },




  uploadScnrImageFile() {
    var that = this;
    var scnrimage = that.data.scnrimage;
    var scnrurls = that.data.scnrurls;
    var musicarr = that.data.musicarr;
    if (scnrimage[0].imgtype==0){
      scnrurls.push(scnrimage[0].PICURL);
      that.setData({
        scnrurls: scnrurls
      })
      that.data.scnrimage.splice(0, 1);
      if (that.data.scnrimage.length > 0){
        that.uploadScnrImageFile();
      } else if (musicarr.length > 0){
        that.uploadMusicFile();
      }else{
        that.savePoteryRead();
      }
    }else{
      wx.uploadFile({
        url: app.myUlife.ulifeUrl + '/upload/uploadScdhFm.html', //上传服务器的地址
        filePath: scnrimage[0].PICURL, //临时路径
        name: 'file',
        header: {
          contentType: "multipart/form-data", //按需求增加
        },
        formData: null,
        success: function (res) {
          var img = JSON.parse(res.data);
          var urls = img.urls;
          scnrurls.push(urls);
          that.setData({
            scnrurls: scnrurls
          })
          that.data.scnrimage.splice(0, 1);
          if (that.data.scnrimage.length > 0) {
            that.uploadScnrImageFile();
          } else if (musicarr.length > 0) {
            that.uploadMusicFile();
          } else {
            that.savePoteryRead();
          }
        },
        fail: function (err) {
          wx.hideLoading();
          console.log(err.errMsg);//上传失败
        }
      });
    }   
  },


  uploadMusicFile() {
    var that = this;
    var musicarr = that.data.musicarr;
    var musicurl = that.data.musicurl;
    if (musicarr[0].playtype == 0) {
      var item={
        yp: musicarr[0].YP,
        mc: musicarr[0].MC
      }
      musicurl.push(item);
      that.setData({
        musicurl: musicurl
      })
      that.data.musicarr.splice(0, 1);
      if (that.data.musicarr.length > 0) {
        that.uploadMusicFile();
      } else {
        that.savePoteryRead();
      }
    }else{
      wx.uploadFile({
        url: app.myUlife.ulifeUrl + '/upload/uploadMusicurl.html', //上传服务器的地址
        filePath: musicarr[0].YP, //临时路径
        name: 'file',
        header: {
          contentType: "multipart/form-data", //按需求增加
        },
        formData: null,
        success: function (res) {
          var img = JSON.parse(res.data);
          var urls = img.urls;
          var item = {
            yp: urls,
            mc: musicarr[0].MC
          }
          musicurl.push(item);
          that.setData({
            musicurl: musicurl
          })
          that.data.musicarr.splice(0, 1);
          if (that.data.musicarr.length > 0) {
            that.uploadMusicFile();
          } else {
            that.savePoteryRead();
          }
        },
        fail: function (err) {
          wx.hideLoading();
          console.log(err.errMsg);//上传失败
        }
      });
    }  
  },


  savePoteryRead() {
    var readid = this.data.readid;
    var pname = this.data.pname;
    var author = this.data.author;
    var nj = this.data.nj;
    var bj = this.data.bj;
    var pcontent = this.data.pcontent;
    var fm = this.data.fm;
    var scnrurls = this.data.scnrurls;//诗词内容图片
    var musicurl = this.data.musicurl;

    wx.request({
      url: app.myUlife.ulifeUrl + 'poetryread/editPoteryRead.html',
      data: {
        readid: readid,
        pname: pname,
        author: author,
        nj: nj,
        bj: bj,
        pcontent: pcontent,
        fm: fm,
        scurls: JSON.stringify(scnrurls),
        musicurls: JSON.stringify(musicurl),
        bstate: '1'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.result) {
          wx.showModal({
            title: '成功',
            content: res.data.msg,
            showCancel: !1,
          });
          wx.reLaunch({
            url: '../../task/mytask/mytask'
          })
        } else {
          that.setData({
            disabled: false,
            loading: false
          })
          wx.showModal({
            title: '失败',
            content: res.data.msg,
            showCancel: !1,
          });
        }
      }
    })
  },






  //..............上传诗词内容图片start.................
  //上传图片
  uploadSCimages: function () {
    var that = this;
    wx.chooseImage({
      count: 4, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        var scnrimage = that.data.scnrimage;
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          var item={
            PICURL: res.tempFilePaths[i],
            imgtype:1
          }
          scnrimage.push(item);
        }
        that.setData({
          scnrimage: scnrimage
        })
      }
    });
  },
  //删除图片
  delSCImage: function (e) {
    var that = this;
    var scnrimage = that.data.scnrimage;
    var cuindex = e.target.dataset.index;
    scnrimage.splice(cuindex, 1);
    that.setData({
      scnrimage: scnrimage
    })
  },
  //预览图片
  viewSCimage: function (e) {
    var cuindex = e.target.dataset.index;
    var that = this;
    var scnrimage = that.data.scnrimage;
    var urls=[];
    for (var k = 0; k < scnrimage.length;k++){
      urls.push(scnrimage[k].PICURL);
    }
    wx.previewImage({
      current: urls[cuindex].PICURL, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
 //..............上传诗词内容图片end.................





  //..............诗词语音播放start.................
  //开始播放
  ksbfsc: function (e) {
    let that = this
    var index = e.currentTarget.dataset.index;
    var musicarr = that.data.musicarr;
    musicarr[index].playStatus = false;
    that.setData({ musicarr: musicarr })
    var musicUrl ="";
    var xturl = that.data.xturl;
    if (musicarr[index].playtype==0){
      musicUrl = xturl + musicarr[index].YP; //音频url
    }else{
      musicUrl = musicarr[index].YP; //音频url
    }
     
    innerAudioContext.src = musicUrl;
    innerAudioContext.autoplay = true
    innerAudioContext.play();
    innerAudioContext.onPlay((res) => {
      innerAudioContext.onTimeUpdate((res) => {
        if (innerAudioContext.duration.toFixed(2) - innerAudioContext.currentTime.toFixed(2) <= 0) {
          that.setStopSCState(index)
        }
        innerAudioContext.onEnded(() => {
          that.setStopSCState(index)
        })
      })
    })
  },
  setStopSCState: function (index) {
    let that = this
    var musicarr = that.data.musicarr;
    musicarr[index].playStatus = true;
    that.setData({ musicarr: musicarr })
    innerAudioContext.seek(0);
    innerAudioContext.stop();
  },
  //结束播放
  canel_playsc(e) {
    let that = this
    var index = e.currentTarget.dataset.index;
    innerAudioContext.pause(); //语音暂停
    var musicarr = that.data.musicarr;
    musicarr[index].playStatus = true;
    that.setData({ musicarr: musicarr })
  },
  delMusic(e) {
    var index = e.currentTarget.dataset.index;
    var musicarr = this.data.musicarr;
    musicarr.splice(index, 1);
    this.setData({
      musicarr: musicarr
    })
  },
//..............诗词语音播放end.................





//..............诗词语音上传弹窗打开start.................
  //诗词语音上传打开
  scyyShow(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.setData({
      musicmc: '',//音频名称
      musicUrl: '',//音频地址
    })
    this.openscyy(currentStatu);
  },


  //打开诗词语音弹窗
  openscyy(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200, //动画时长  
      timingFunction: "linear", //线性  
      delay: 0 //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })
      //关闭  
      if (currentStatu == "close") {
        this.setData({
          showxdthplModalStatus: false
        });
      }
    }.bind(this), 200)
    // 显示  
    if (currentStatu == "open") {
      this.setData({
        showxdthplModalStatus: true
      });
    }
  },

  //确定诗词语音
  sureScyy() {
    var musicmc = this.data.musicmc;
    var musicUrl = this.data.musicUrl;
    if (musicmc == "") {
      wx.showModal({
        title: '失败',
        content: "请填写语音名称",
        showCancel: !1,
      });
      return;
    }
    if (musicUrl == "") {
      wx.showModal({
        title: '失败',
        content: "请上传语音！",
        showCancel: !1,
      });
      return;
    }
    var musicarr = this.data.musicarr;
    var mu = {
      MC: musicmc,
      YP: musicUrl,
      playStatus: true,
      playtype:1
    }
    musicarr.push(mu);
    this.setData({
      musicarr: musicarr
    });

    this.openscyy('close');
  },
//..............诗词语音上传弹窗打开end.................

})